﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web.Script.Serialization;

namespace BSF.Tool
{
    /// <summary>  
    /// Json序列化和反序列化辅助类   
    /// </summary>  
    public static class JsonHelper
    {
        /*
           在c#项目中有时会用到json格式字符串和对象数据类型的转换，下面是一个转换工具类：
           说明：根据Json字符串生成对象时,是根据对应的属性名称赋值,多于或少于都不会报错. 
           使用“DataContractJsonSerializer ”类时需要：
           1、引用程序集 System.Runtime.Serialization 和 System.ServiceModel.Web
           2、导入命名空间 System.Runtime.Serialization 和 System.Runtime.Serialization.Json
           使用“JavaScriptSerializer ”类时需要：
           1、引用程序集 System.Web.Extension
           2、导入命名空间 System.Web.Script.Serialization
            
            var req = "{ url:\"Controller/getConfig\", param: [{url:\"Controller/getConfig1\", param:{pageIndex:1, pageSize:8}},{url:\"Controller/getConfig2\", param:{pageIndex:1, pageSize:8}}] }";
            //Newtonsoft.Json序列化和反序列 http://james.newtonking.com/json
            //RequestobjModel deserializedProduct = (RequestobjModel)JsonConvert.DeserializeObject(req, typeof(RequestobjModel));
            //RequestobjModel deserializedProduct = (RequestobjModel)JavaScriptConvert.DeserializeObject(output, typeof(RequestobjModel));
            //string output = JavaScriptConvert.SerializeObject(list);
            object obj = JsonConvert.DeserializeObject(req);
            JObject js = obj as JObject;
            JArray ja = js["param"] as JArray;
            //foreach (var item in ja.Children())
            //{
            //    var itemProperties = item.Children<JProperty>();
            //    //you could do a foreach or a linq here depending on what you need to do exactly with the value
            //    var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
            //    var myElementValue = myElement.Value; ////This is a JValue type
            //}
            //List<string> uidlist = new List<string>();
            //for (int i = 0; i < ja.Count; i++)//foreach (JProperty i in json.Children()) //遍历JSON对象的所有属性
            //{
            //    JObject jo = ja[i] as JObject;
            //    uidlist.Add(jo["url"].ToString());
            //}
            ////序列化：
            //string jsonStr= JsonConvert.SerializeObject(person);//person为实例化之后的对象
            ////反序列化：
            //Person person = (Person)JsonConvert.DeserializeObject(jsonStr, typeof(Person));
            ////序列化：
            //JavaScriptSerializer jss = new JavaScriptSerializer();
            //string jsonStr= jss.Serialize(person);
            ////反序列化：
            //Person p1=jss.Deserialize(jsonStr);

            //var req = "[{url:\"Tbda_customer/ChildTask1\", param:{pageIndex:1, pageSize:8}},{url:\"Home/ChildTask2\", param:{pageIndex:1, pageSize:8}}]";
            //JArray ja = JArray.Parse(req);
            var list = new List<RequestobjModel>();
            for (int i = 0; i < ja.Count; i++)//foreach (JProperty i in json.Children()) //遍历JSON对象的所有属性
            {
                var _model = new RequestobjModel();
                JObject jo = ja[i] as JObject;
                _model.url = jo["url"].ToString();
                JObject jarr = jo["param"] as JObject;
                var tempparamjson = string.Empty;
                foreach (JProperty xp in jarr.Children())
                {
                    tempparamjson += string.Concat(xp.Name, "=", xp.Value, "&");
                }
                _model.param = tempparamjson.TrimEnd('&');
                list.Add(_model);
            }
            
         */
        /// <summary>   
        /// Json序列化   
        /// </summary>   
        public static string JsonSerializer<T>(T obj)
        {
            string jsonString = string.Empty;
            try
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));

                using (MemoryStream ms = new MemoryStream())
                {
                    serializer.WriteObject(ms, obj);
                    jsonString = Encoding.UTF8.GetString(ms.ToArray());
                }
            }
            catch
            {
                jsonString = string.Empty;
            }
            return jsonString;
        }

        /// <summary>   
        /// Json反序列化  
        /// </summary>   
        public static T JsonDeserialize<T>(string jsonString)
        {
            T obj = Activator.CreateInstance<T>();
            try
            {
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
                {
                    DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType());//typeof(T)  
                    T jsonObject = (T)ser.ReadObject(ms);
                    ms.Close();

                    return jsonObject;
                }
            }
            catch
            {
                return default(T);
            }
        }

        // 将 DataTable 序列化成 json 字符串  
        public static string DataTableToJson(DataTable dt)
        {
            if (dt == null || dt.Rows.Count == 0)
            {
                return "\"\"";
            }
            JavaScriptSerializer myJson = new JavaScriptSerializer();

            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();

            foreach (DataRow dr in dt.Rows)
            {
                Dictionary<string, object> result = new Dictionary<string, object>();
                foreach (DataColumn dc in dt.Columns)
                {
                    result.Add(dc.ColumnName, dr[dc].ToString());
                }
                list.Add(result);
            }
            return myJson.Serialize(list);
        }

        // 将对象序列化成 json 字符串  
        public static string ObjectToJson(object obj)
        {
            if (obj == null)
            {
                return string.Empty;
            }
            JavaScriptSerializer myJson = new JavaScriptSerializer();

            return myJson.Serialize(obj);
        }

        // 将 json 字符串反序列化成对象  
        public static object JsonToObject(string json)
        {
            if (string.IsNullOrEmpty(json))
            {
                return null;
            }
            JavaScriptSerializer myJson = new JavaScriptSerializer();

            return myJson.DeserializeObject(json);
        }

        // 将 json 字符串反序列化成对象  
        public static T JsonToObject<T>(string json)
        {
            if (string.IsNullOrEmpty(json))
            {
                return default(T);
            }
            JavaScriptSerializer myJson = new JavaScriptSerializer();

            return myJson.Deserialize<T>(json);
        }

        /// <summary>
        /// 序列化对象转JSON字串
        /// </summary>
        /// <param name="m_Model"></param>
        /// <returns></returns>
        public static string SerializeJson(object m_Model)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            return js.Serialize(m_Model);
        }

        /// <summary>
        /// 反序列化JSON字串转T对象
        /// 参考字串：{RoleName:'角色2',ShopName:'店铺2'}
        /// 参考IList字串：[{\"RoleName\":\"角色1\",\"ShopName\":\"店铺1\"},{\"RoleName\":\"角色2\",\"ShopName\":\"店铺2\"}]
        /// </summary>
        /// <param name="p_JsonStr"></param>
        /// <returns></returns>
        public static T DeserializeJson<T>(string p_JsonStr)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            return js.Deserialize<T>(p_JsonStr);
        }

        #region json
        static JavaScriptSerializer GetJSS()
        {
            return new JavaScriptSerializer();
        }

        public static string ToJson(object obj)
        {
            var jss = GetJSS();
            return jss.Serialize(obj);
        }

        public static void ToJson(object obj, StringBuilder output)
        {
            var jss = GetJSS();
            jss.Serialize(obj, output);
        }

        public static T JsonTo<T>(string json)
        {
            var jss = GetJSS();
            T obj = jss.Deserialize<T>(json);
            return obj;
        }

        public static object JsonTo(string json, Type targetType)
        {
            var jss = GetJSS();
            var obj = jss.DeserializeObject(json);
            return obj;
        }

        #endregion
    }
}
